<template>
  <div class="material">
    <el-card>
      <div class="material-search">
        <el-form ref="form" :inline="true" label-width="130px" :model="form">
          <el-form-item label="设备编号：">
            <el-input v-model="form.EQUIPMENT_ID" />
          </el-form-item>
          <el-form-item label="设备型号：">
            <el-input v-model="form.EQUIPMENT_MODEL" />
          </el-form-item>
          <el-form-item label="品牌：">
            <el-select v-model="form.BRAND_ID" clearable placeholder="请选择">
              <el-option v-for="item in brandOptions" :key="item.BRAND_ID" :label="item.BRAND_NAME" :value="item.BRAND_ID" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型：">
            <el-cascader v-model="form.TYPE_ID" clearable :options="typeOptions" placeholder="请选择" :props="props" :show-all-levels="false" />
          </el-form-item>
          <el-form-item label="能否实现封闭式：">
            <el-select v-model="form.BE_CLOSED" clearable placeholder="请选择">
              <el-option v-for="item in budgetUnit.closed" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="场地温度类型：">
            <el-select v-model="form.TEMPERATURE_TYPE" clearable placeholder="请选择">
              <el-option v-for="item in budgetUnit.temperatureType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">重置</el-button>
            <el-button type="primary" @click="query">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="material-table">
        <div class="btns">
          <div>
            <el-button type="primary" @click="addFacility">新增设备</el-button>
            <el-button @click="toLead">导入数据</el-button>
          </div>
          <el-button @click="derive">导出</el-button>
        </div>
        <el-table border :data="list" highlight-current-row>
          <el-table-column label="设备编号" prop="EQUIPMENT_ID" width="100" />
          <el-table-column label="品牌" prop="BRAND_NAME" />
          <el-table-column label="设备类型" prop="TYPE_NAME" />
          <el-table-column label="设备型号" prop="EQUIPMENT_MODEL" />
          <el-table-column label="场地温度类型" prop="TEMPERATURE_TYPE" />
          <el-table-column label="能否实现封闭式" prop="BE_CLOSED" />
          <el-table-column label="长（mm）" prop="LENGTH" />
          <el-table-column label="宽（mm）" prop="WIDTH" />
          <el-table-column label="高（mm）" prop="HEIGHT" />
          <el-table-column label="自定义1" prop="UDF1" />
          <el-table-column label="自定义2" prop="UDF2" />
          <el-table-column label="自定义3" prop="UDF3" />
          <el-table-column label="创建人员" prop="ADDWHO" />
          <el-table-column label="创建时间" prop="ADDTIME" />
          <el-table-column label="修改人员" prop="EDITWHO" />
          <el-table-column label="修改时间" prop="EDITTIME" />
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" @click="editor(row)">编辑</el-button>
              <el-button type="text" @click="dele(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :page-size="size"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="addVisible" :title="title" width="50%">
      <material-form v-if="addVisible" @success="success" />
    </el-dialog>
    <el-dialog v-model="editorVisible" :title="title" width="50%">
      <material-form v-if="editorVisible" :equipment-one-id="equipmentOneId" @success="success" />
    </el-dialog>
    <el-dialog v-model="uploadVisible" title="设备上传" width="80%">
      <div>
        <el-steps :active="active" align-center>
          <el-step title="上传模版数据" />
          <el-step title="模版数据检测" />
          <el-step title="单据建立完成" />
        </el-steps>
        <div class="step-two">
          <div v-if="active == 1">
            <div class="hint_">
              <p class="hint-title">特别提示</p>
              <p class="hint-explain">请使用系统要求模板按格式要求填写数据，填写完成进行数据上传</p>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <div>
                <p>填写导入数据信息</p>
                <p>请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
                <el-button type="text" @click="download">下载模板</el-button>
              </div>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <vui-upload
                ref="fileUploadRef"
                class="text-left"
                :file-name="uploadOptions.name"
                :limit="1"
                :post-data="uploadOptions.postData"
                :url="uploadOptions.url"
                @uploadSuccess="uploadSuccess"
              >
                <div>
                  <p>上传填好的信息表</p>
                  <p>文件后缀名必须为xls或xlsx(既Excel格式)，文件大小不得大于10M</p>
                  <el-button v-if="!file" size="small" type="text">上传文件</el-button>
                </div>
              </vui-upload>
            </div>
            <div class="footer_">
              <el-button type="primary" @click="clickUpload">下一步</el-button>
            </div>
          </div>
          <div v-if="active == 2">
            <div v-if="abnormal">
              <div class="box_" style="height: 80px">
                <div class="left-box"></div>
                <div>
                  <p>正常数量条数：{{ errorData.successNumber }}</p>
                  <p>
                    异常数量条数：
                    <span style="color: red">{{ errorData.failNumber }}</span>
                  </p>
                </div>
              </div>
              <div class="abnormal-hint">
                <p>异常提示</p>
                <template v-for="(item, index) in errorData.errorInfoList" :key="index">
                  <p style="color: red">
                    {{ item }}
                  </p>
                </template>
              </div>
            </div>
          </div>
          <div v-if="active == 3">
            <div>
              <p>数据导入成功</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import budgetUnit from '../../common/options'
  import MaterialForm from '../../components/materialForm.vue'
  import requestMethod from '../../common/requestMethod'
  import publicFn from '../../common/requestCommon'
  import { GFCD } from '@/utils/utils'
  import { download } from '../../api/home'
  const configSetting = GFCD('bqms')
  export default {
    name: 'Material',
    components: {
      MaterialForm,
    },
    emits: ['cancel'],
    data() {
      return {
        active: 1,
        uploadOptions: {
          postData: {
            method: requestMethod.MATERIAL_IMPORT,
            data: JSON.stringify({ TEMP_TYPE: 'EQUIPMENT_MATERIAL' }),
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        title: '新增设备',
        list: [],
        form: {},
        budgetUnit,
        size: 10,
        total: 0,
        currentPage: 1,
        addVisible: false,
        editorVisible: false,
        equipmentOneId: '',
        brandOptions: [],
        typeOptions: [],
        srcArr: [],
        uploadVisible: false,
        props: {
          emitPath: false, //绑定的内容只获取最后一级的value值。
        },
        formEnd: {},
      }
    },
    created() {
      this.getBrand()
      this.getTypeList()
    },
    activated() {
      this.list = []
      this.form = {}
    },
    methods: {
      async derive() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: requestMethod.MATERIAL_EXPORT,
          data: JSON.stringify({
            '#EXPORT_WHERE#': this.form,
            '#EXPORT_SQL_ID#': requestMethod.EQUIPMENT_LIST,
            '#EXPORT_API_NAME#': requestMethod.EQUIPMENT_LIST,
            '#QUERY_SORT#': {},
            '#EXPORT_FILE_NAME#': '',
            '#EXPORT_FILE_TYPE#': 'xlsx',
            '#EXPORT_SHEET_NAME#': '',
            '#EXPORT_COLUMN#': {
              EQUIPMENT_ID: '设备编号',
              EQUIPMENT_BRAND: '品牌',
              EQUIPMENT_TYPE: '设备类型',
              TEMPERATURE_TYPE: '场地温度类型',
              BE_CLOSED: '能否实现封闭式',
              LENGTH: '长',
              WIDTH: '宽',
              UDF1: '自定义1',
              UDF2: '自定义2',
              UDF3: '自定义2',
              ADDWHO: '创建人员',
              ADDTIME: '创建时间',
              EDITWHO: '修改人员',
              EDITTIME: '修改时间',
            },
          }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '物料设备.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      clickUpload() {
        if (this.$refs['fileUploadRef'].allImgNum) {
          this.$refs['fileUploadRef'].submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: '请选择文件',
          })
        }
      },
      async threeNext() {
        let res = await publicFn(requestMethod.IMPORT_SP, this.formEnd)
        if (res.code === '00000') {
          this.active++
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        console.log(res)
        if (res.code === '00000') {
          this.uploadList = res.data.importData
          this.formEnd.FILE_PATH = res.data.filePath
          this.formEnd.FILE_NAME = res.data.fileName
          this.formEnd.FILE_HIS_NAME = res.data.originalFileName
          this.active++
          this.abnormal = false
          this.threeNext()
        } else if (res.code === 'S0055') {
          this.errorData.successNumber = res.count
          this.errorData.failNumber = res.data.length
          this.errorData.errorInfoList = res.data
          this.$message({
            type: 'error',
            message: res.msg,
          })
          this.abnormal = true
          this.active++
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      async download() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: requestMethod.TEMPLATE_DOWNLOAD,
          data: JSON.stringify({ TEMP_TYPE: 'EQUIPMENT_MATERIAL' }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '物料设备模板.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      cancel() {
        this.uploadVisible = false
      },
      toLead() {
        this.uploadVisible = true
      },
      editor(row) {
        this.equipmentOneId = row.EQUIPMENT_ID
        this.editorVisible = true
        this.title = '编辑设备'
      },
      async getTypeList() {
        let res = await publicFn(requestMethod.TYPE_LIST, { '#LIMIT#': 1, '#PAGE_SIZE#': 99999 })
        console.log(res)
        if (res.code === '00000') {
          this.srcArr = res.data[requestMethod.TYPE_LIST].data
          res.data[requestMethod.TYPE_LIST].data.forEach((item) => {
            if (item.PARAENT_TYPE_ID == 0) {
              this.typeOptions.push({
                parentId: item.PARAENT_TYPE_ID,
                value: item.TYPE_ID,
                label: item.TYPE_NAME,
                children: [],
              })
            }
          })
          this.typeOptions.forEach((it) => {
            it.children = this.getChildren(it.value, this.srcArr)
          })
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      // 处理级联--递归
      getChildren(tId, srcArr) {
        let children = []
        srcArr.forEach((item) => {
          if (item.PARAENT_TYPE_ID == tId) {
            children.push({
              parentId: item.PARAENT_TYPE_ID,
              value: item.TYPE_ID,
              label: item.TYPE_NAME,
              children: [],
            })
          }
        })
        if (children.length == 0) {
          return null
        }
        children.forEach((item) => {
          item.children = this.getChildren(item.value, this.srcArr)
        })
        return children
      },
      async getBrand() {
        let res = await publicFn(requestMethod.BRAND_LIST, { '#LIMIT#': 1, '#PAGE_SIZE#': 99999 })
        if (res.code === '00000') {
          this.brandOptions = res.data[requestMethod.BRAND_LIST].data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      dele(row) {
        this.$confirm('此操作将删除该设备, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await publicFn(requestMethod.EQUIPMENT_ONE_DELETE, { EQUIPMENT_ID: row.EQUIPMENT_ID })
            console.log(res)
            if (res.code === '00000') {
              this.query()
            } else {
              this.$message({
                type: 'info',
                message: res.msg,
              })
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      //获取设备列表
      async getEquipment() {
        let res = await publicFn(requestMethod.EQUIPMENT_LIST, { ...this.form, '#LIMIT#': this.currentPage, '#PAGE_SIZE#': this.size })
        if (res.code === '00000') {
          this.total = res.data[requestMethod.EQUIPMENT_LIST].count
          this.list = res.data[requestMethod.EQUIPMENT_LIST].data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      query() {
        this.getEquipment()
      },
      reset() {
        this.form = {}
        this.query()
      },
      success() {
        this.addVisible = false
        this.editorVisible = false
        this.query()
      },
      addFacility() {
        this.addVisible = true
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.query()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .material {
    padding: 15px;
    box-sizing: border-box;
    .material-search,
    .material-table {
      border: 1px solid #f5f5f5;
    }
    .material-table {
      margin-top: 20px;
      .btns {
        padding: 0 0 15px 0;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .hint_ {
    background: #fff5e6;
    padding: 15px 30px;
    box-sizing: border-box;
    .hint-title {
      font-weight: 600;
    }
    .hint-explain {
      margin-top: 10px;
    }
  }
  .step-two {
    margin-top: 20px;
  }
  .box_ {
    margin-top: 20px;
    display: flex;
    align-items: center;
    height: 115px;
    border: 1px solid #d8d3d3;
    p {
      margin-top: 10px;
    }
  }
  .left-box {
    background: #f5f5f5;
    width: 50px;
    height: 100%;
  }
  .abnormal-hint {
    padding: 15px;
    margin-top: 20px;
    box-sizing: border-box;
    border: 1px solid #f5f5f5;
    p {
      margin-top: 10px;
    }
  }
  .success {
    display: flex;
    justify-content: center;
    align-items: center;
    & > div {
      height: 300px;
    }
  }
</style>
